//
//  CBaseRequest.m
//  CedarSuperCloud
//
//  Created by lshenrong on 2017/11/24.
//  Copyright © 2017年 cedarhd. All rights reserved.
//

#import "CedarBaseRequest.h"
#import "PlatformTools.h"
#import "YTKNetworkConfig.h"
#import "CedarTools.h"
#import "CedarBaseResponse.h"
#import "CedarDataBaseStore.h"
#import "RSA.h"
#import "CedarTipsManager.h"
#import "NetworkManager.h"

@interface CedarBaseRequest()

@property (nonatomic,strong) CedarBaseResponse * _Nullable cedarResponse;


@end

@implementation CedarBaseRequest

- (instancetype)init{
    if (self = [super init]) {
        self.isNotShowErrorTips = NO;
        self.requestSpecialHandle = SpecialHandleTypeDefault;
    }
    return self;
}

- (NSTimeInterval)requestTimeoutInterval{
    return 15;
}

- (CedarBaseResponse *)cedarResponse{
    if (!_cedarResponse) {
        _cedarResponse = [[CedarBaseResponse alloc]init];
    }
    return _cedarResponse;
}


- (void)requestCompleteFilter{
    [super requestCompleteFilter];
#if DEBUG
    NSString * str  =[[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
    BigCLog(@"%@ response: \n%@\n",NSStringFromClass([self class]),str);
    
#endif
    if (self.requestSpecialHandle == SpecialHandleTypeLogin) {
        NSString *token = self.responseHeaders[@"token"];
        if (token) {
            [[CedarDataBaseStore shareInstance] setTokenForAppConfige:token];
            CLog(@"save token :%@",token);
        }
    }
    {
        NSError *error;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableContainers error:&error];
        if([dict isKindOfClass: [NSDictionary class] ]) {
            NSString *codeNumber = [dict objectForKey:@"code"];
            self.cedarResponse.code = codeNumber.integerValue;
            self.cedarResponse.message = [dict objectForKey:@"message"];
            if (self.cedarResponse.code == ResponseTypeScuess) {
                self.cedarResponse.dataObject = [dict objectForKey:@"body"];
            }else{
                if(self.cedarResponse.code == ResponseTypeTokenExpired){//token失效 回到首页
                    [[CedarDataBaseStore shareInstance] setTokenForAppConfige:nil];
                    [[CedarDataBaseStore shareInstance] saveLoginInfo:nil];
                    [self publish:Logout_Notification data:nil];
                    if ([self.cedarResponse.msg length]>0) {
                        [CedarTipsManager showTipsInWindowWithOnlyText:self.cedarResponse.msg];
                    }
                    return;
                }else if(self.cedarResponse.code == ResponseTypeUnauthorized){//没有登录信息
                    if ([self.cedarResponse.msg containsString:@"没有登录信息"]) {
                        [[CedarDataBaseStore shareInstance] setTokenForAppConfige:nil];
                        [[CedarDataBaseStore shareInstance] saveLoginInfo:nil];
                        [self publish:Logout_Notification data:nil];
                        if ([self.cedarResponse.msg length]>0) {
                            [CedarTipsManager showTipsInWindowWithOnlyText:self.cedarResponse.msg];
                        }
                        CLog(@"No LoginToken");
                        return;
                    }
                }
                if (!self.isNotShowErrorTips){
                    if ([self.cedarResponse.msg length]>0 && self.cedarResponse.code != 1013) {
                        [CedarTipsManager showTipsInWindowWithOnlyText:self.cedarResponse.msg];
                    }
                }
            }
        }
    }
}

- (void)requestFailedFilter{
    [super requestFailedFilter];
    if (!self.isCancelled){
        if (!self.isNotShowErrorTips) {
            [CedarTipsManager showTipsInWindowWithOnlyText:@"当前网络不佳，请稍后再试!"];
        }
    }
}

- (void)startCedarRequestWithCompletionBlock:(nullable CedarRequestCompletionBlock)result{
   /* if ([NetworkManager shareInstance].networkReachabilityStatus == CedarNetworkReachabilityNoneNet) {
        if (result) {
            self.cedarResponse.code = ResponseTypeNoNet;
            result(self.cedarResponse);
        }
        if (!self.isNotShowErrorTips) {
            [CedarTipsManager showTipsInWindowWithOnlyText:@"无网络"];
        }
        return;
    }*/
    [self startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
         if (result) {
            result(self.cedarResponse);
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (result) {
            result(self.cedarResponse);
        }
    }];
}

- (id)requestAppendArgument{
    return @{};
}

#pragma mark - custom url

- (NSURLRequest *)buildCustomUrlRequest{
    NSString *baseUrl = [YTKNetworkConfig sharedConfig].baseUrl;
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",baseUrl,[self requestUrl]];
    NSMutableURLRequest * mutableRequest = [[NSMutableURLRequest alloc ] initWithURL: [NSURL URLWithString: urlStr] cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 20.0];
    [mutableRequest setHTTPMethod:@"POST"];
    [mutableRequest setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [mutableRequest setValue:@"" forHTTPHeaderField:@"Accept"];
  
//    if (self.requestSpecialHandle != SpecialHandleTypeLogin){
//        NSString *token = [[CedarDataBaseStore shareInstance] getTokenForAppConfige];
//
//        if (token) {
//            [mutableRequest setValue:token forHTTPHeaderField:@"token"];
//        }else{
//            CLog(@"token is nil");
//        }
//    }
    NSString *channel = @"ios";
    NSString *requestTime = [PlatformTools getCurrentTime];
    NSString *requestHost = [[NetworkManager shareInstance] currentDeviceIP];
    NSString *appVersion = [PlatformTools appVersion];
    NSDictionary *appDic = [self requestAppendArgument];
    NSDictionary * arguDict = nil;
    if (appDic) {
        NSString *appdendJsonStr =  [self convertToJsonData:appDic];
#if DEBUG
        NSString *token1 = [[CedarDataBaseStore shareInstance] getTokenForAppConfige];
        CLog(@"API: %@,URL: %@,request params: %@, token: %@, requestHost: %@",NSStringFromClass([self class]),urlStr,appdendJsonStr,token1,requestHost);
#endif
        arguDict = @{
//                     @"channel":channel,
//                     @"requestTime":requestTime,
//                     @"version":appVersion,
//                     @"requestHost":requestHost,
//                     @"flag":@(1),
                     @"body":appdendJsonStr
                     };
    
    }else{
        arguDict = @{
                     @"channel":channel,
                     @"requestTime":requestTime,
                     @"version":appVersion,
                     @"flag":@(1),
                     @"requestHost":requestHost
                     };
        
        
  
    }
    NSString *appdendJsonStr =  [self convertToJsonData:appDic];
    NSData *bodyData = [appdendJsonStr dataUsingEncoding:NSUTF8StringEncoding];
    [mutableRequest setHTTPBody: bodyData ];
    return mutableRequest;
}

#if DEBUG
- (void)dealloc{
    NSLog(@"request class  %@ dealloc",NSStringFromClass([self class]));
}
#endif

- (NSString *)convertToJsonData:(NSDictionary *)dict {
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        return nil;
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}


@end
